package com.woorigil.social;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

public class HttpUtils {
	public static String getHtml(String mainUrl) {
		try {
			URL url = new URL(mainUrl);
			URLConnection connection = url.openConnection();
			BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));

			StringBuffer buf = new StringBuffer();
			while (true) {
				String line = br.readLine();
				if (line == null) {
					break;
				}
				buf.append(line);
			}
			return buf.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static String execute(String url) throws Exception {
        return execute(url, 7000);
	}
	
	public static String execute(String url, int setTimeout) throws Exception {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, setTimeout);
		HttpConnectionParams.setSoTimeout(params, setTimeout);
		
		HttpGet method = new HttpGet(url);
		method.setHeader("Connection", "Keep-Alive");
		method.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0");	
		HttpResponse response = httpClient.execute(method);
		int status = response.getStatusLine().getStatusCode();
		if (status != HttpStatus.SC_OK) {
			throw new Exception( "http response status error!! status is " + status );
		}
		return EntityUtils.toString( response.getEntity(), "UTF-8" );
	}	
}
